import pygame, sys, os, time, webbrowser
from pygame.locals import *

import playership, alienship, shot

# jag ar inte saker pa namnet, men det kan vi ju andra sen. ps. aao gillas inte av python om man inte skriver ENCODING BLA BLA BLA langst upp :D
class GameEngine:
    def __init__(self):
        self.width = 800
        self.height = 600
        self.hero = playership.PlayerShip(self.width/2, self.height-20, self.width, self.height, "ship.png")
        self.alien = alienship.AlienShip(self.width/2, 0, "alien1.png", self.hero)
        self.frame = 0
        
        self.gameHazards = [self.alien]
        self.alien = alienship.AlienShip(self.width, 0, "alien1.png", self.hero)
        self.gameHazards.append(self.alien)
        self.gameObjects = [self.hero]

    def update(self):
        for o in self.gameObjects:
            o.update()
        for object in self.gameHazards:
            if not object.update():
                self.gameHazards.remove(object)
        for h in self.gameHazards:
            if (self.collision(self.hero, h)):
                self.hero.hit()
        self.frame += 1

    def eventKeyDown(self, key):
        #if playing bla bla bla, annars kanske EN MENY :D
        self.hero.eventKeyDown(key)
        if key == K_SPACE:
            s = shot.Shot(self.hero.x, self.hero.y, 0, -15, "shot.png")
            self.gameObjects.append(s)
            s.update()
    
    def eventKeyUp(self, key):
        #if playing bla bla bla, annars kanske EN MENY :D
        self.hero.eventKeyUp(key)

    def collision(self, a, b):
        left1 = a.x
        right1 = a.surface.get_width() + a.x
        left2 = b.x
        right2 = b.surface.get_width() + b.x
        bot1 = a.y
        top1 = a.y + a.surface.get_height()
        bot2 = b.y
        top2 = b.y + b.surface.get_height()

        if left1 > right2:
            return False
        if left2 > right1:
            return False
        if bot1 > top2:
            return False
        if bot2 > top1:
            return False
        return True

